package com.rz.paas.test.viewPager

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.rz.paas.test.R

class BannerViewPager(context: Context, attributeSet: AttributeSet? = null) :
    ViewPager(context, attributeSet) {

    lateinit var mAdapter: BannerAdapter
    private val mContnetView by lazy {
        mutableListOf<View>()
    }

    fun setAdapter(adapter: BannerAdapter) {
        this.mAdapter = adapter
        setAdapter(BannerPagerAdapter())
    }

    inner class BannerPagerAdapter : PagerAdapter() {
        override fun getCount(): Int {
            return Int.MAX_VALUE
        }

        override fun isViewFromObject(view: View, obj: Any): Boolean {
            return view == obj
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            val bannerItemView = mAdapter.getView(position % mAdapter.getCount(), getContentView())
            container.addView(bannerItemView)
            bannerItemView.findViewById<Button>(R.id.change).setOnClickListener {
                nextPage()
            }
            return bannerItemView
        }

        override fun destroyItem(container: ViewGroup, position: Int, obj: Any) {
            container.removeView(obj as View)
            mContnetView.add(obj)
        }
    }

    fun getContentView(): View? {
        for (index in 0 until mContnetView.size) {
            if (mContnetView.get(index).parent == null) {
                return mContnetView.get(index)
            }
        }
        return null
    }

    fun nextPage(){
        currentItem += 1
    }

}